package com.mapbar.mongodb;

import java.net.UnknownHostException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBAddress;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.QueryOperators;
import com.mongodb.WriteConcern;
import com.mongodb.WriteResult;

public class DBCollectionTester {
	public static void main(String[] args) throws UnknownHostException {
		DB db = Mongo.connect(new DBAddress("192.168.51.114", 20000, "dbtest"));
		DBCollection collection = db.getCollection("news");

		collection.drop();// 删除集合
		collection.apply(getExampleBasicDBObject("我操你妈的中国政府", "Lv9"));// 将记录添加到缓冲中随时添加入库
		collection.apply(getExampleBasicDBObject("我还操你妈的中国政府", "Lv15"), true);// 将记录添加到缓冲中随时添加入库 并且选择是否添加ID字段

		insertTest(collection);
		distinctTest(collection);
		findAndModifyTest(collection);
		findTest(collection);

		collection.createIndex(new BasicDBObject("push_time", 1));// 强制创建索引
		collection.ensureIndex(new BasicDBObject("author", 1));// 创建索引
		collection.ensureIndex(new BasicDBObject("title", 1), new BasicDBObject("name", "t_index"));// 创建索引并且携带部分选项(比如指定索引名称)

		System.err.println(collection.findOne());// 返回一条记录 可以指定ID 或者其他查询条件
		System.err.println(collection.count());// 查询集合中记录总数
		System.err.println(collection.count(new BasicDBObject("author", "sina")));// 查询集合中记录总数(指定条件)
		System.err.println(collection.getCollection("authors").findOne());// 获取子集合
		System.err.println(db.getLastError());

		collection.dropIndexes();// 删除索引
		// db.dropDatabase();
	}

	public static void findAndModifyTest(DBCollection collection) {
		BasicDBObject update = new BasicDBObject();

		update.put("$set", new BasicDBObject("is_changed", true));
		update.put("$inc", new BasicDBObject("click_count", 2000));

		BasicDBObject fields = new BasicDBObject();
		fields.put("title", true);
		fields.put("author", true);
		fields.put("push_time", true);

		System.err.println("findAndModify start");
		System.err.println(collection.findAndModify(new BasicDBObject("author", "sina"), update));// 不能批量更新..
		System.err.println(collection.findAndRemove(new BasicDBObject("author", "sohu")));// 查询并删除记录
		System.err.println(collection.findAndModify(new BasicDBObject("author", "sohu"), fields, new BasicDBObject("push_time", 1), true, null, false, false));
		System.err.println("findAndModify end");
	}

	public static void findTest(DBCollection collection) {
		DBCursor cursor = collection.find();
		System.err.println("find start");
		while (cursor.hasNext()) {
			DBObject result = cursor.next();
			System.err.println("        " + result);
		}
		System.err.println("find end");
		cursor.close();

		BasicDBObject param = new BasicDBObject();

		param.put("click_count", new BasicDBObject("$gt", 1000));
		param.put("author", new BasicDBObject(QueryOperators.IN, new String[] { "sina", "baidu" }));// 嵌套执行查询

		BasicDBObject attr = new BasicDBObject();

		attr.put("title", true);
		attr.put("author", true);
		attr.put("_id", false);

		cursor = collection.find(param, attr);

		System.err.println("find start");
		while (cursor.hasNext()) {
			DBObject result = cursor.next();
			System.err.println("        " + result);
		}
		System.err.println("find end");
	}

	public static void distinctTest(DBCollection collection) {
		List<?> keys = collection.distinct("author");// 查询指定列的唯一值(还有个重载函数 附加查询条件)
		System.err.println("distinct start");

		for (Object key : keys) {
			System.err.println("        " + key);
		}

		System.err.println("distinct end");
	}

	public static void insertTest(DBCollection collection) {
		collection.insert(getExampleBasicDBObject("北京上海等地银行首套房贷利率现折扣优惠", "baidu"));
		collection.insert(getExampleBasicDBObject("油价上涨的蝴蝶效应将显 或致CPI再次高企", "baidu"));
		collection.insert(getExampleBasicDBObject("CSDN网站用户数据泄露案告破 5名嫌疑人落网", "baidu"));
		collection.insert(getExampleBasicDBObject("江苏“美女老板”欠6亿跑路 涉案金额或超吴英", "baidu"));
		collection.insert(getExampleBasicDBObject("盗窃团伙开“全国代表大会”被警方一锅端", "baidu"));

		collection.insert(getExampleBasicDBObject("乌克兰两名官二代残害少女", "sina"));
		collection.insert(getExampleBasicDBObject("国务院批准广东千亿元养老金投资运营", "sina"));
		collection.insert(getExampleBasicDBObject("人民日报评刑诉法第73条争议:公众担心执法部门滥用", "sina"));
		collection.insert(getExampleBasicDBObject("李源潮：党的干部要做全社会思想道德的模范", "sina"));
		collection.insert(getExampleBasicDBObject("物流联合会呼吁撤并高速公路不合理收费站点", "sina"));
		collection.insert(getExampleBasicDBObject("亚冠-朴成破门北京1-1", "sina"));
		collection.insert(getExampleBasicDBObject("”高富帅”遇女嘉宾返场表白", "sina"));

		List<DBObject> objects = new LinkedList<DBObject>();

		objects.add(getExampleBasicDBObject("刑诉法第73条引发争议 公众担心执法部门滥用", "qq"));
		objects.add(getExampleBasicDBObject("中国海监将常态化巡航钓鱼岛 削弱日本实际控制", "qq"));
		objects.add(getExampleBasicDBObject("人民日报：警察随意上街盘查公民易引发冲突", "qq"));
		objects.add(getExampleBasicDBObject("司法部要求律师执业必须宣誓忠于国家拥护党", "qq"));
		objects.add(getExampleBasicDBObject("青岛黑老大聂磊称将上诉 政法机关毁涉黑证据", "qq"));
		objects.add(getExampleBasicDBObject("央行调查显示我国居民购房意愿降至历史最低", "qq"));
		objects.add(getExampleBasicDBObject("网传北京合理房价4935/平", "sohu"));
		objects.add(getExampleBasicDBObject("专家云南发现未知古人群化石 具混合特征(图)", "sohu"));
		objects.add(getExampleBasicDBObject("郑州街头公安宣传报被倒贴 市民称太粗心(图)", "sohu"));

		WriteResult result = collection.insert(objects, WriteConcern.NORMAL);

		System.err.println("---------------------------------------------------------" + result.getError());
	}

	public static BasicDBObject getExampleBasicDBObject(String title, String author) {
		BasicDBObject object = new BasicDBObject();
		object.put("title", title);
		object.put("author", author);
		object.put("click_count", generator.nextInt(2000));
		object.put("push_time", new Date());

		List<BasicDBObject> posts = new LinkedList<BasicDBObject>();

		for (int i = 0; i < 3; i++) {
			BasicDBObject post = new BasicDBObject();
			post.put("username", "Lv" + i);
			post.put("message", i + "L");

			posts.add(post);
		}
		object.put("posts", posts);
		return object;
	}

	public static final Random generator = new Random();
}
